<template>
  <div class="demo-page">
    <!-- 粒子背景 -->
    <div class="particles-background" ref="particlesContainer"></div>
    
    <!-- 主要内容 -->
    <div class="demo-content">
      <!-- Hero 区域 -->
      <section class="hero-section">
        <div class="hero-content">
          <h1 class="hero-title" ref="heroTitle">炫酷效果演示</h1>
          <p class="hero-subtitle" ref="heroSubtitle">体验前沿的 Web 动画技术</p>
          <div class="hero-tags">
            <span class="tech-tag">Three.js</span>
            <span class="tech-tag">GSAP</span>
            <span class="tech-tag">CSS3</span>
            <span class="tech-tag">WebGL</span>
          </div>
        </div>
      </section>

      <!-- 效果展示区域 -->
      <section class="effects-showcase">
        <div class="showcase-grid">
          <!-- 3D 迷宫 404 -->
          <div class="effect-card" @click="navigateToEffect('/error/404')">
            <div class="card-content">
              <div class="card-icon">🌀</div>
              <h3 class="card-title">3D 迷宫探索</h3>
              <p class="card-description">精神错乱的 404 页面，让用户在迷宫中寻找出路</p>
              <div class="card-tech">
                <span class="tech-badge">Three.js</span>
                <span class="tech-badge">GSAP</span>
              </div>
            </div>
            <div class="card-overlay"></div>
          </div>

          <!-- 故障艺术 500 -->
          <div class="effect-card" @click="navigateToEffect('/error/500')">
            <div class="card-content">
              <div class="card-icon">⚡</div>
              <h3 class="card-title">故障艺术效果</h3>
              <p class="card-description">赛博朋克风格的 500 错误页面，带有故障艺术效果</p>
              <div class="card-tech">
                <span class="tech-badge">CSS Glitch</span>
                <span class="tech-badge">Animation</span>
              </div>
            </div>
            <div class="card-overlay"></div>
          </div>

          <!-- 高级加载动画 -->
          <div class="effect-card" @click="showLoadingDemo">
            <div class="card-content">
              <div class="card-icon">🧬</div>
              <h3 class="card-title">高级加载动画</h3>
              <p class="card-description">DNA 螺旋、神经网络等多种科幻加载效果</p>
              <div class="card-tech">
                <span class="tech-badge">GSAP</span>
                <span class="tech-badge">SVG</span>
              </div>
            </div>
            <div class="card-overlay"></div>
          </div>

          <!-- 音频可视化 -->
          <div class="effect-card" @click="showAudioDemo">
            <div class="card-content">
              <div class="card-icon">🎵</div>
              <h3 class="card-title">音频可视化</h3>
              <p class="card-description">实时音频频谱分析和 3D 可视化效果</p>
              <div class="card-tech">
                <span class="tech-badge">Web Audio</span>
                <span class="tech-badge">WebGL</span>
              </div>
            </div>
            <div class="card-overlay"></div>
          </div>

          <!-- 粒子系统 -->
          <div class="effect-card" @click="showParticleDemo">
            <div class="card-content">
              <div class="card-icon">✨</div>
              <h3 class="card-title">粒子系统</h3>
              <p class="card-description">交互式粒子效果，鼠标跟随和重力模拟</p>
              <div class="card-tech">
                <span class="tech-badge">Canvas</span>
                <span class="tech-badge">Physics</span>
              </div>
            </div>
            <div class="card-overlay"></div>
          </div>

          <!-- 3D 场景 -->
          <div class="effect-card" @click="show3DDemo">
            <div class="card-content">
              <div class="card-icon">🎲</div>
              <h3 class="card-title">3D 交互场景</h3>
              <p class="card-description">Three.js 驱动的 3D 场景，支持鼠标交互</p>
              <div class="card-tech">
                <span class="tech-badge">Three.js</span>
                <span class="tech-badge">WebGL</span>
              </div>
            </div>
            <div class="card-overlay"></div>
          </div>
        </div>
      </section>

      <!-- 返回按钮 -->
      <div class="back-button">
        <NuxtLink to="/" class="back-link">
          <span class="back-icon">←</span>
          返回首页
        </NuxtLink>
      </div>
    </div>

    <!-- 加载演示组件 -->
    <AdvancedLoading 
      v-if="showLoading"
      :visible="showLoading"
      :type="loadingType"
      :title="loadingTitle"
      :subtitle="loadingSubtitle"
      @complete="hideLoadingDemo"
    />

    <!-- 音频可视化演示 -->
    <div v-if="showAudio" class="audio-demo-overlay" @click="hideAudioDemo">
      <div class="audio-demo-content" @click.stop>
        <h3>音频可视化演示</h3>
        <p>点击播放按钮开始音频可视化</p>
        <button @click="startAudioVisualization" class="demo-btn">开始演示</button>
        <div class="audio-visualizer" ref="audioVisualizer"></div>
        <button @click="hideAudioDemo" class="close-btn">关闭</button>
      </div>
    </div>

    <!-- 粒子演示 -->
    <div v-if="showParticle" class="particle-demo-overlay" @click="hideParticleDemo">
      <div class="particle-demo-content">
        <h3>粒子系统演示</h3>
        <p>移动鼠标与粒子互动</p>
        <canvas ref="particleCanvas" class="particle-canvas"></canvas>
        <button @click="hideParticleDemo" class="close-btn">关闭</button>
      </div>
    </div>

    <!-- 3D 演示 -->
    <div v-if="show3D" class="threejs-demo-overlay" @click="hide3DDemo">
      <div class="threejs-demo-content">
        <h3>3D 交互场景</h3>
        <p>拖拽鼠标旋转 3D 模型</p>
        <div ref="threejsContainer" class="threejs-container"></div>
        <button @click="hide3DDemo" class="close-btn">关闭</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { gsap } from 'gsap'
import * as THREE from 'three'
import AdvancedLoading from '~/components/Loading/AdvancedLoading.vue'

// GSAP ScrollTrigger 插件
let ScrollTrigger
if (typeof window !== 'undefined') {
  import('gsap/ScrollTrigger').then((module) => {
    ScrollTrigger = module.ScrollTrigger
    gsap.registerPlugin(ScrollTrigger)
  })
}

// 响应式数据
const particlesContainer = ref(null)
const heroTitle = ref(null)
const heroSubtitle = ref(null)
const audioVisualizer = ref(null)
const particleCanvas = ref(null)
const threejsContainer = ref(null)

const showLoading = ref(false)
const showAudio = ref(false)
const showParticle = ref(false)
const show3D = ref(false)

const loadingType = ref('dna')
const loadingTitle = ref('加载中...')
const loadingSubtitle = ref('正在为您准备精彩内容')

// 动画引用
let particleAnimation, audioContext, audioSource, analyser
let particleSystem, threejsScene, threejsRenderer, threejsCamera

// 页面 SEO
useHead({
  title: '炫酷效果演示 - 前端技术展示',
  meta: [
    { name: 'description', content: '展示 Three.js、GSAP 等前端技术的炫酷效果' }
  ]
})

// 创建背景粒子
function createBackgroundParticles() {
  if (!particlesContainer.value) return

  const particleCount = 100
  for (let i = 0; i < particleCount; i++) {
    const particle = document.createElement('div')
    particle.className = 'bg-particle'
    particle.style.left = Math.random() * 100 + '%'
    particle.style.top = Math.random() * 100 + '%'
    particle.style.animationDelay = Math.random() * 5 + 's'
    particle.style.animationDuration = (5 + Math.random() * 10) + 's'
    
    // 随机大小和颜色
    const size = 2 + Math.random() * 4
    particle.style.width = size + 'px'
    particle.style.height = size + 'px'
    
    const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7']
    particle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]
    
    particlesContainer.value.appendChild(particle)
  }
}

// 启动入场动画
function startEntryAnimations() {
  // Hero 标题动画
  gsap.fromTo(heroTitle.value, 
    { 
      opacity: 0, 
      scale: 0.8,
      rotationY: 90
    },
    { 
      opacity: 1, 
      scale: 1, 
      rotationY: 0,
      duration: 1.5, 
      ease: "back.out(1.7)" 
    }
  )

  // Hero 副标题动画
  gsap.fromTo(heroSubtitle.value,
    { opacity: 0, y: 30 },
    { opacity: 1, y: 0, duration: 1, delay: 0.5, ease: "power3.out" }
  )

  // 技术标签动画
  gsap.fromTo('.tech-tag',
    { opacity: 0, scale: 0, rotation: 180 },
    { 
      opacity: 1, 
      scale: 1, 
      rotation: 0,
      duration: 0.8, 
      delay: 1, 
      stagger: 0.1,
      ease: "back.out(1.7)" 
    }
  )

  // 卡片进入动画
  gsap.fromTo('.effect-card',
    { opacity: 0, y: 50, rotationX: -45 },
    { 
      opacity: 1, 
      y: 0, 
      rotationX: 0,
      duration: 1, 
      delay: 1.5, 
      stagger: 0.2,
      ease: "power3.out"
    }
  )
}

// 导航到效果页面
function navigateToEffect(path) {
  gsap.to('.demo-page', {
    duration: 0.5,
    opacity: 0,
    scale: 0.95,
    ease: 'power2.inOut',
    onComplete: () => {
      navigateTo(path)
    }
  })
}

// 显示加载演示
function showLoadingDemo() {
  const loadingTypes = ['dna', 'code', 'neural', 'geometry']
  const titles = ['DNA 解析中...', '代码编译中...', '神经网络训练中...', '几何变换中...']
  const subtitles = ['正在分析遗传密码', '正在编译未来科技', '正在构建智能网络', '正在重塑现实']
  
  const randomIndex = Math.floor(Math.random() * loadingTypes.length)
  loadingType.value = loadingTypes[randomIndex]
  loadingTitle.value = titles[randomIndex]
  loadingSubtitle.value = subtitles[randomIndex]
  
  showLoading.value = true
}

// 隐藏加载演示
function hideLoadingDemo() {
  showLoading.value = false
}

// 显示音频演示
function showAudioDemo() {
  showAudio.value = true
}

// 隐藏音频演示
function hideAudioDemo() {
  showAudio.value = false
  if (audioContext) {
    audioContext.close()
    audioContext = null
  }
}

// 开始音频可视化
async function startAudioVisualization() {
  try {
    // 创建音频上下文
    audioContext = new (window.AudioContext || window.webkitAudioContext)()
    
    // 创建振荡器作为音频源
    const oscillator = audioContext.createOscillator()
    analyser = audioContext.createAnalyser()
    
    oscillator.connect(analyser)
    analyser.connect(audioContext.destination)
    
    oscillator.frequency.setValueAtTime(440, audioContext.currentTime)
    oscillator.start()
    
    // 开始可视化
    visualizeAudio()
    
    setTimeout(() => {
      oscillator.stop()
    }, 5000)
    
  } catch (error) {
    console.error('音频可视化失败:', error)
  }
}

// 音频可视化动画
function visualizeAudio() {
  if (!analyser || !audioVisualizer.value) return
  
  const canvas = document.createElement('canvas')
  canvas.width = 400
  canvas.height = 200
  audioVisualizer.value.appendChild(canvas)
  
  const ctx = canvas.getContext('2d')
  const dataArray = new Uint8Array(analyser.frequencyBinCount)
  
  function draw() {
    requestAnimationFrame(draw)
    
    analyser.getByteFrequencyData(dataArray)
    
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    const barWidth = canvas.width / dataArray.length
    let x = 0
    
    for (let i = 0; i < dataArray.length; i++) {
      const barHeight = (dataArray[i] / 255) * canvas.height
      
      const gradient = ctx.createLinearGradient(0, canvas.height - barHeight, 0, canvas.height)
      gradient.addColorStop(0, '#ff6b6b')
      gradient.addColorStop(1, '#4ecdc4')
      
      ctx.fillStyle = gradient
      ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight)
      
      x += barWidth
    }
  }
  
  draw()
}

// 显示粒子演示
function showParticleDemo() {
  showParticle.value = true
  setTimeout(startParticleSystem, 100)
}

// 隐藏粒子演示
function hideParticleDemo() {
  showParticle.value = false
  if (particleSystem) {
    particleSystem = null
  }
}

// 启动粒子系统
function startParticleSystem() {
  const canvas = particleCanvas.value
  if (!canvas) return
  
  canvas.width = 600
  canvas.height = 400
  const ctx = canvas.getContext('2d')
  
  const particles = []
  const mouse = { x: 0, y: 0 }
  
  // 创建粒子
  for (let i = 0; i < 100; i++) {
    particles.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      vx: (Math.random() - 0.5) * 2,
      vy: (Math.random() - 0.5) * 2,
      radius: Math.random() * 3 + 1,
      color: `hsl(${Math.random() * 360}, 70%, 60%)`
    })
  }
  
  // 鼠标事件
  canvas.addEventListener('mousemove', (e) => {
    const rect = canvas.getBoundingClientRect()
    mouse.x = e.clientX - rect.left
    mouse.y = e.clientY - rect.top
  })
  
  // 动画循环
  function animate() {
    if (!showParticle.value) return
    
    ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    
    particles.forEach(particle => {
      // 鼠标吸引
      const dx = mouse.x - particle.x
      const dy = mouse.y - particle.y
      const distance = Math.sqrt(dx * dx + dy * dy)
      
      if (distance < 100) {
        particle.vx += dx * 0.0001
        particle.vy += dy * 0.0001
      }
      
      // 更新位置
      particle.x += particle.vx
      particle.y += particle.vy
      
      // 边界检测
      if (particle.x < 0 || particle.x > canvas.width) particle.vx *= -1
      if (particle.y < 0 || particle.y > canvas.height) particle.vy *= -1
      
      // 绘制粒子
      ctx.beginPath()
      ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2)
      ctx.fillStyle = particle.color
      ctx.fill()
    })
    
    requestAnimationFrame(animate)
  }
  
  animate()
}

// 显示 3D 演示
function show3DDemo() {
  show3D.value = true
  setTimeout(start3DScene, 100)
}

// 隐藏 3D 演示
function hide3DDemo() {
  show3D.value = false
  if (threejsRenderer) {
    threejsRenderer.dispose()
    threejsRenderer = null
  }
}

// 启动 3D 场景
function start3DScene() {
  const container = threejsContainer.value
  if (!container) return
  
  // 场景设置
  threejsScene = new THREE.Scene()
  threejsCamera = new THREE.PerspectiveCamera(75, 600 / 400, 0.1, 1000)
  threejsRenderer = new THREE.WebGLRenderer({ antialias: true })
  
  threejsRenderer.setSize(600, 400)
  threejsRenderer.setClearColor(0x000011)
  container.appendChild(threejsRenderer.domElement)
  
  // 创建几何体
  const geometry = new THREE.BoxGeometry(2, 2, 2)
  const material = new THREE.MeshPhongMaterial({ 
    color: 0x44aa88,
    shininess: 100
  })
  const cube = new THREE.Mesh(geometry, material)
  threejsScene.add(cube)
  
  // 光照
  const light = new THREE.DirectionalLight(0xffffff, 1)
  light.position.set(5, 5, 5)
  threejsScene.add(light)
  
  const ambientLight = new THREE.AmbientLight(0x404040, 0.4)
  threejsScene.add(ambientLight)
  
  // 摄像机位置
  threejsCamera.position.z = 5
  
  // 鼠标控制
  let mouseX = 0, mouseY = 0
  
  container.addEventListener('mousemove', (e) => {
    mouseX = (e.offsetX / 600) * 2 - 1
    mouseY = (e.offsetY / 400) * 2 - 1
  })
  
  // 动画循环
  function animate3D() {
    if (!show3D.value) return
    
    cube.rotation.x += 0.01
    cube.rotation.y += 0.01
    
    // 鼠标控制
    cube.rotation.x += mouseY * 0.02
    cube.rotation.y += mouseX * 0.02
    
    threejsRenderer.render(threejsScene, threejsCamera)
    requestAnimationFrame(animate3D)
  }
  
  animate3D()
}

// 组件挂载
onMounted(() => {
  // 创建背景粒子
  createBackgroundParticles()
  
  // 启动入场动画
  setTimeout(startEntryAnimations, 100)
  
  // 鼠标跟随效果
  document.addEventListener('mousemove', (e) => {
    const cursor = document.querySelector('.custom-cursor')
    if (cursor) {
      cursor.style.left = e.clientX + 'px'
      cursor.style.top = e.clientY + 'px'
    }
  })
})

// 组件卸载
onUnmounted(() => {
  if (particleAnimation) particleAnimation.kill()
  if (audioContext) audioContext.close()
  if (threejsRenderer) threejsRenderer.dispose()
})
</script>

<style scoped>
.demo-page {
  min-height: 100vh;
  background: radial-gradient(circle at 50% 50%, #1a1a2e, #16213e, #0f0f23);
  overflow-x: hidden;
  position: relative;
}

/* 背景粒子 */
.particles-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
  pointer-events: none;
}

.bg-particle {
  position: absolute;
  border-radius: 50%;
  animation: float 10s infinite linear;
  opacity: 0.6;
}

@keyframes float {
  0% {
    transform: translateY(100vh) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 0.6;
  }
  90% {
    opacity: 0.6;
  }
  100% {
    transform: translateY(-10vh) rotate(360deg);
    opacity: 0;
  }
}

/* 主要内容 */
.demo-content {
  position: relative;
  z-index: 10;
  padding: 2rem;
}

/* Hero 区域 */
.hero-section {
  text-align: center;
  padding: 4rem 0;
  margin-bottom: 4rem;
}

.hero-title {
  font-size: 4rem;
  font-weight: bold;
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4, #45b7d1, #96ceb4);
  background-size: 400% 400%;
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  animation: gradientShift 4s ease infinite;
  margin: 0 0 1rem 0;
  text-shadow: 0 0 30px rgba(255, 255, 255, 0.3);
}

.hero-subtitle {
  font-size: 1.5rem;
  color: #cccccc;
  margin: 0 0 2rem 0;
  opacity: 0.9;
}

.hero-tags {
  display: flex;
  justify-content: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.tech-tag {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 2rem;
  font-size: 0.9rem;
  font-weight: 500;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.tech-tag:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

@keyframes gradientShift {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* 效果展示区域 */
.effects-showcase {
  max-width: 1200px;
  margin: 0 auto;
}

.showcase-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 2rem;
}

/* 效果卡片 */
.effect-card {
  position: relative;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 1rem;
  padding: 2rem;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

.effect-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transform: translateX(-100%);
  transition: transform 0.6s ease;
}

.effect-card:hover::before {
  transform: translateX(100%);
}

.effect-card:hover {
  transform: translateY(-10px) scale(1.02);
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.3);
}

.card-content {
  position: relative;
  z-index: 2;
}

.card-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  display: block;
}

.card-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: white;
  margin: 0 0 1rem 0;
}

.card-description {
  color: #cccccc;
  line-height: 1.6;
  margin: 0 0 1.5rem 0;
}

.card-tech {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.tech-badge {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
  padding: 0.3rem 0.8rem;
  border-radius: 1rem;
  font-size: 0.8rem;
  border: 1px solid rgba(255, 107, 107, 0.3);
}

/* 返回按钮 */
.back-button {
  text-align: center;
  margin-top: 4rem;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  color: white;
  text-decoration: none;
  padding: 1rem 2rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.back-link:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.back-icon {
  font-size: 1.2rem;
}

/* 演示覆盖层 */
.audio-demo-overlay,
.particle-demo-overlay,
.threejs-demo-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.9);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.audio-demo-content,
.particle-demo-content,
.threejs-demo-content {
  background: rgba(255, 255, 255, 0.1);
  padding: 2rem;
  border-radius: 1rem;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  text-align: center;
  color: white;
  max-width: 90%;
}

.audio-demo-content h3,
.particle-demo-content h3,
.threejs-demo-content h3 {
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
}

.demo-btn,
.close-btn {
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
  margin: 1rem 0.5rem;
  transition: all 0.3s ease;
}

.demo-btn:hover,
.close-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.audio-visualizer {
  margin: 1rem 0;
  min-height: 200px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
}

.particle-canvas {
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  margin: 1rem 0;
}

.threejs-container {
  margin: 1rem 0;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-title {
    font-size: 2.5rem;
  }
  
  .hero-subtitle {
    font-size: 1.2rem;
  }
  
  .showcase-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .effect-card {
    padding: 1.5rem;
  }
  
  .demo-content {
    padding: 1rem;
  }
}
</style>
